package com.lpx.demo.demo.util;

import com.lpx.demo.demo.entity.BaseUserEntity;
import org.springframework.util.ObjectUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

public class SessionUtils {
    /**
     * set注入
     * 获取 httpServletRequest
     */
    private static HttpServletRequest getRequest() {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes attributes = (ServletRequestAttributes) requestAttributes;
        if (ObjectUtils.isEmpty(attributes)) {return null;}
        return attributes.getRequest();
    }
    /**
     * 根据session key 获取value
     * @param key
     * @return
     */
    public static Object getSessionValue(String key){
        HttpServletRequest request = getRequest();
        return request.getSession().getAttribute(key);
    }

    /**
     * 获取 User
     * @return
     */
    public static BaseUserEntity getUser(){
        return  (BaseUserEntity) getSessionValue(Constant.user);

    }
}
